﻿using System.IO;
using System.Text;

namespace FitAutomation.FitProcess
{

	public class Message
	{
		readonly byte[] _buf;

		public Message(byte[] buf)
		{
			_buf = buf;
		}

		static readonly Encoding _encoding = Encoding.UTF8;

		public string AsString
		{
			get { return _encoding.GetString(_buf); }
		}

		public Message(string message)
		{
			_buf = _encoding.GetBytes(message);
		}

		public Message(Stream stream)
		{
			using(var br = new BinaryReader(stream))
			{
				_buf = br.ReadBytes(unchecked((int) stream.Length));
			}
		}

		const byte _mc = 254;

		public Message(MessageCode message)
		{
			_buf = new[] {_mc, (byte) message};
		}

		public static implicit operator Message(byte[] message)
		{
			return new Message(message);
		}

		public static implicit operator Message(string message)
		{
			return new Message(message);
		}

		public static implicit operator Message(Stream message)
		{
			return new Message(message);
		}

		public static implicit operator Message(MessageCode message)
		{
			return new Message(message);
		}

		public static implicit operator byte[](Message message)
		{
			return message._buf;
		}

		public static implicit operator MessageCode(Message message)
		{
			if (message._buf.Length == 2)
			{
				if (message._buf[0] == _mc)
				{
					return (MessageCode)message._buf[1];
				}
			}
			return MessageCode.ErrorNotMessageCode;
		}

		public static implicit operator string(Message message)
		{
			return message.AsString;
		}

	}
}